package com.zzyl.service.impl;

import com.google.common.collect.Lists;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.MemberService;
import com.zzyl.service.WechatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.vo.LoginVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Condition;

/**
 * @Description MemberServiceImpl
 * @Author KangChi Wang
 * @Date 2024-08-30
 */
@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {

        //1.远程调用接口获取openid
        String openId = wechatService.getOpenid(userLoginRequestDto.getCode());

        //2.根据openid查询数据库member用户
        Member member = memberMapper.getByOpenId(openId);

        //3.判断member用户是否为空
        if (member == null) {
            //3.1 为空，创建Member对象封装openid
            member = Member.builder()
                    .openId(openId)
                    .build();
        }

        //4.远程调用接口获取手机号
        String phone = wechatService.getPhone(userLoginRequestDto.getPhoneCode());

        //5.判断用户是否注册过（member的id是否为空）
        if (member.getId() != null) {
            //5.1 判断手机号是否一致
            if (!member.getPhone().equals(phone)) {
                //不一致，更新数据库
                member.setPhone(phone);
                memberMapper.update(member);
            }
        }
        //5.1 如果注册过，判断手机号是否一致，不一致更新数据库
        if (member.getId() == null) {
            //6.封装手机号到member
            member.setPhone(phone);
            //6.1 封装昵称
            //随机组装昵称，词组+手机号后四位
            String nickName = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size()))
                    + StringUtils.substring(member.getPhone(), 7);
            //6.2 插入操作
            member.setName(nickName);
            memberMapper.save(member);
        }



        //6.封装LoginVo返回
        LoginVo loginVo = new LoginVo();
        //6.1 封装nickName
        loginVo.setNickName(member.getName());
        //6.2 封装token
        //定义载荷
        Map<String, Object> map=new HashMap<>();
        map.put(Constants.JWT_USERID, member.getId());
        map.put(Constants.JWT_USERNAME, member.getName());
        //生成令牌
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl(), map);
        System.out.println("token=============================================:"+token);

        loginVo.setToken(token);
        System.out.println("loginVo=============================================:"+loginVo.getToken());

        //7.返回
        return loginVo;
    }
}
